package com.xd.navi;

import android.content.IntentFilter;
import android.net.ConnectivityManager;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import java.util.ArrayList;
import java.util.List;

public class NetWorkManager implements DefaultLifecycleObserver {

    private static final NetWorkManager S_MANAGER = new NetWorkManager();
    private NetworkReceive mNetworkStateReceive;

    private List<OnNetStateChangeListener> mNetStateChangeListeners;

    private NetWorkManager() {
        mNetStateChangeListeners = new ArrayList<>();
    }

    public static NetWorkManager getInstance() {
        return S_MANAGER;
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        mNetworkStateReceive = new NetworkReceive();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        Utils.getApp().getApplicationContext().registerReceiver(mNetworkStateReceive, filter);
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        Utils.getApp().getApplicationContext().unregisterReceiver(mNetworkStateReceive);
    }

    public void addListener(OnNetStateChangeListener listener) {
        mNetStateChangeListeners.add(listener);
    }

    public void removeListener(OnNetStateChangeListener listener) {
        mNetStateChangeListeners.remove(listener);
    }

    public void notifyNetStateChange(boolean isConnect) {
        for (OnNetStateChangeListener listener : mNetStateChangeListeners) {
            listener.onNetStateChange(isConnect);
        }
    }
}
